using System.Collections.Generic;
using System.Threading;

namespace SS.Common.Threading.JobExecutor
{
    #region Used namespaces

    

    #endregion

    /// <summary>
    /// An Implementation of IJobExecutor using common System.Threading.ThreadPool
    /// </summary>
    /// <typeparam name="T">The type of jobs those need to be executed</typeparam>
    public class SystemThreadPoolJobExecutor<T> : IJobExecutor<T>
        where T : IJob
    {
        /// <summary>
        /// Init the executor
        /// </summary>
        public void Initialize()
        {
        }

        /// <summary>
        /// Queue a job
        /// </summary>
        /// <param name="job">The job to queue</param>
        public void Queue(T job)
        {
            WaitCallback callBack = ThreadPoolCallback;
            ThreadPool.QueueUserWorkItem(callBack, job);
        }

        /// <summary>
        /// Stop the executor
        /// </summary>
        /// <param name="force">
        /// Force stop, do not wait for a long time
        /// </param>
        /// <returns>
        /// Empty list as not check for remain tasks
        /// </returns>
        public List<T> Stop(bool force)
        {
            // No way to cancel the queued work items
            return new List<T>();
        }

        /// <summary>
        /// Wait for the executor terminated
        /// Note currently not supported
        /// </summary>
        /// <param name="millisecondsTimeout">
        /// Timeout in milliseconds
        /// </param>
        /// <returns>
        /// false as no implementation
        /// </returns>
        public bool WaitForTermination(int millisecondsTimeout)
        {
            // No way to indentify which job has been done
            return false;
        }

        /// <summary>
        /// Clean up the executor
        /// </summary>
        public void Dispose()
        {
            this.Stop(true);
        }

        /// <summary>
        /// The call back implementation that neccessary for the thread pool
        /// </summary>
        /// <param name="obj">The executable job</param>
        private static void ThreadPoolCallback(object obj)
        {
            if (obj is T)
            {
                ((T)obj).Execute();
            }
        }
    }
}
